#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from dws.commons.common import log
from common.util.check_utils import is_valid_id
from common.common import exter_attack
from common.parse_parafile import ParamFileUtil
from dws.commons.dws_param_parse import DwsParamParse
from dws.commons.job_info import JobInfo
from dws.backup.cluster_backup import ClusterBackup


@exter_attack
def do_exec(pid):
    log.info(f"Enter, pid:{pid}")
    param = ParamFileUtil.parse_param_file(pid)

    job_info = JobInfo(pid=pid,
                       job_id=DwsParamParse.get_job_id(param),
                       copy_id=DwsParamParse.get_copy_id(param),
                       sub_job_id=DwsParamParse.get_sub_job_id(param),
                       usr=DwsParamParse.get_user_name(param),
                       env_path=DwsParamParse.get_env_path(param))
    log.info(f'{job_info}')

    try:
        if not ClusterBackup(pid).abort_backup(job_info):
            raise Exception(f'Abort backup failed')
    except Exception as err_str:
        log.error(f"Abort backup failed err: {err_str}, {job_info.log_format()}")
        return False

    log.info(f"Abort backup suc, {job_info.log_format()}")
    return True


if __name__ == '__main__':
    if len(sys.argv) < 4:
        log.error("Param is wrong.")
        sys.exit(1)

    if not is_valid_id(sys.argv[1]):
        log.warn(f"pid is invalid")
        sys.exit(1)
    try:
        if not do_exec(sys.argv[1]):
            log.error(f"Abort job do_exec failed, pid: {sys.argv[1]}.")
    except Exception as err:
        log.error(f"Abort job err: {err}, pid: {sys.argv[1]}")
        sys.exit(1)

    sys.exit(0)
